    //
//  MAWebViewController.m
//  MAdaptorV2
//
//  Created by chenwei on 12-05-24.
//  Copyright 2012 TechEase. All rights reserved.
//

#import "MAWebViewController.h"
#import "RequestServer.h"

@implementation MAWebViewController
@synthesize webView;

- (void)viewDidLoad {
	
	[super viewDidLoad];
	self.contentSizeForViewInPopover = CGSizeMake(300, 400);
	
	webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
	webView.autoresizingMask = AutoresizingFull;
	
	[self.view addSubview:webView];
	
	webView.delegate = self;
	webView.scalesPageToFit = YES;
	webView.userInteractionEnabled = YES;
	webView.backgroundColor = [UIColor clearColor];
	//webViewCtrl.opaque = NO;
    UIBarButtonItem *bar =[[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(selectCancelAction:)];
    self.navigationItem.leftBarButtonItem = bar;
}

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request 
 navigationType:(UIWebViewNavigationType)navigationType {
	//NSURL *url = request.URL;
	//NSString *urlString = url.absoluteString;

	return YES;	
}

#pragma mark ---- UIWebView代理方法 ----
//开始加载数据
- (void)webViewDidStartLoad:(UIWebView *)webView { 
//	[[MAServerDAO instance] performSelector:@selector(startWaitCursor)];
}

//数据加载完
- (void)webViewDidFinishLoad:(UIWebView *)webview {
//	[[MAServerDAO instance] performSelector:@selector(stopWaitCursor)];
	
	self.title = [webview stringByEvaluatingJavaScriptFromString:@"document.title"];
}


- (void) selectCancelAction: (id) sender {
	[self.navigationController popViewControllerAnimated:YES];
}

- (void)loadHTMLfromURL:(NSString*)strUrl {
	[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[strUrl stringByURLEncodingStringParameter]]]];
}

- (void)loadHTMLString:(NSString*)htmlString {	
	//[myWebView loadHTMLString:htmlstring  baseURL:[NSURL fileURLWithPath:[ [NSBundle mainBundle] bundlePath]]];
	webView.scalesPageToFit = YES;
	[webView loadHTMLString:htmlString baseURL:nil];
}
@end


@interface MAFileWebViewController(Private)<RequestServerDelegate>
- (void) loadFile2WebView:(NSString*)filePath;
@end

@implementation MAFileWebViewController
@synthesize fileInfo = _fileInfo;


- (void) setFileInfo:(NSMutableDictionary *)info {
	//[[RequestServer instance] downloadFileAsync:0 withUrl:[info objectForKey:@"url"] withDelegate:self];
}

-(void) doFinished:(NSNumber*)code 
       withMessage:(NSString*)message
          withData:(id) data {
    if (code == 0) {
        [self loadFile2WebView:(NSString*)data];
        
//        // 兼容MServer
//        NSFileManager *filemanager = [NSFileManager defaultManager];
//        if ([filemanager fileExistsAtPath:(NSString*)data]) {
//            NSDictionary *attributes = [filemanager attributesOfItemAtPath:(NSString*)data error:nil];
//            NSNumber *fileSize;
//            if (fileSize = [attributes objectForKey:NSFileSize]) {
//                if ([fileSize intValue] > 0) {
//                    return;
//                } 
//            } 
//        } 
//        [MAUIToolkit showMessage:@"文件下载失败"];
    }
    else {
        ShowMessage(message);
    }
}
- (void) loadFile2WebView:(NSString*)filePath {
	NSURL* fileUrl = [NSURL fileURLWithPath:filePath];
	NSURLRequest *req = [NSURLRequest requestWithURL:fileUrl];
	//解决图片下载后默认显示远小于原图的问题。
	NSString* szExtension = [[filePath pathExtension] lowercaseString];
	if ([szExtension isEqualToString:@"png"] || [szExtension isEqualToString:@"bmp"] ||
		[szExtension isEqualToString:@"jpg"] || [szExtension isEqualToString:@"jpeg"] ||
		[szExtension isEqualToString:@"gif"] || [szExtension isEqualToString:@"psd"] ||
		[szExtension isEqualToString:@"swf"]) {
		UIImage *image = [UIImage imageWithContentsOfFile:filePath];
		CGSize size = [image size];
		NSString *imageHTML = nil;
		if (size.width <= self.view.width && size.height <= self.view.height) {
			NSString *htmlString = @"<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>"
			@"<html xmlns='http://www.w3.org/1999/xhtml'>"
			@"<head>"
			@"<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />"
			@"</head>"
			@"<body><img src='%@' width='%f' height='%f'></body>"
			@"</html>";
			imageHTML  = [NSString stringWithFormat:htmlString, fileUrl, size.width, size.height];
		} else if (size.width <= self.view.width || size.height <= self.view.height) {
			NSString *htmlString = @"<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>"
			@"<html xmlns='http://www.w3.org/1999/xhtml'>"
			@"<head>"
			@"<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />"
			@"<style type='text/css'>.customImg{%@='%f'}</style>"
			@"</head>"
			@"<body><img src='%@' class='customImg'></body>"
			@"</html>";
			imageHTML  = [NSString stringWithFormat:htmlString, ((size.width <= self.view.width) ? @"width" : @"height"),
						  ((size.width <= self.view.width) ? size.width : size.height), fileUrl];
		} else if (size.width <= size.height) {
			NSString *htmlString = @"<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>"
			@"<html xmlns='http://www.w3.org/1999/xhtml'>"
			@"<head>"
			@"<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />"
			@"<style type='text/css'>.customImg{width='%f'}</style>"
			@"</head>"
			@"<body><img src='%@' class='customImg'></body>"
			@"</html>";
			imageHTML  = [NSString stringWithFormat:htmlString, self.view.width, fileUrl];
		} else {
			NSString *htmlString = @"<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>"
			@"<html xmlns='http://www.w3.org/1999/xhtml'>"
			@"<head>"
			@"<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />"
			@"<style type='text/css'>.customImg{height='%f'}</style>"
			@"</head>"
			@"<body><img src='%@' class='customImg'></body>"
			@"</html>";
			imageHTML  = [NSString stringWithFormat:htmlString, self.view.height, fileUrl];
		}
		if (imageHTML) {
			[self loadHTMLString:imageHTML];
		}
	} else if ([szExtension isEqualToString:@"html"] || [szExtension isEqualToString:@"htm"]) {
		NSData *htmlData = [NSData dataWithContentsOfFile:filePath];  
		[self.webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:[NSURL URLWithString:@"http://iphoneincubator.com"]]; 
		self.webView.scalesPageToFit = YES;
	}
	else {
		self.webView.scalesPageToFit = YES;
		[self.webView loadRequest:req];
	}
}

@end